<?php
/**
 * Created by PhpStorm.
 * User: shx
 * Date: 2016/11/17
 * Time: 10:31
 */

namespace App\Helpers;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class Wx {
    const WX_API = 'https://api.weixin.qq.com';

    private $client;
    private $app_id;
    private $app_secret;
    private $my_wx = 'qiyiguotv2016';

    public function __construct($app_id, $app_secret)
    {
        $this->app_id = $app_id;
        $this->app_secret = $app_secret;


        $this->client = new Client([
            'base_uri' => self::WX_API
        ]);
    }


    public function getInput(Request $request)
    {
        $xml = $request->getContent();
        $xml = preg_replace('#\s#', '', $xml);

        return simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    }

    public function getUserInfo($open_id)
    {
        $query = [
            'lang' => 'zh_CN',
            'access_token' => $this->getToken(),
            'openid' => $open_id
        ];

        $response = $this->client->request('GET', '/cgi-bin/user/info', ['query' => $query]);

        return (array)json_decode($response->getBody());
    }

    public function getToken()
    {
        if (!Cache::has('wx.token')) {
            $token = $this->getToken4API();
            Cache::put('wx.token', $token->access_token, $token->expires_in/60 - 10);
        }

        return Cache::get('wx.token');
    }

    public function sendText($openid, $msg)
    {
        $time = time();

        return
<<<RESPONSE
        <xml>
            <ToUserName><![CDATA[{$openid}]]></ToUserName>
            <FromUserName><![CDATA[{$this->my_wx}]]></FromUserName>
            <CreateTime>{$time}</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[{$msg}]]></Content>
        </xml>
RESPONSE;
    }

    private function getToken4API()
    {
        $query = [
            'grant_type' => 'client_credential',
            'appid' => $this->app_id,
            'secret' => $this->app_secret
        ];

        $response = $this->client->request('GET', '/cgi-bin/token', ['query' => $query]);

        return json_decode($response->getBody());
    }
}